Page({
  data: {
    bookingRecords: []
  },

  onLoad: function() {
    this.loadBookingRecords();
  },

  onShow: function() {
    this.loadBookingRecords();
  },

  // 加载预约记录
  loadBookingRecords: function() {
    const that = this;
    wx.getStorage({
      key: 'bookingRecords',
      success: function(res) {
        // 更新状态（根据日期判断是否已使用）
        const records = res.data.map(record => {
          const bookingDateTime = new Date(record.date + ' ' + record.time);
          const now = new Date();
          
          if (bookingDateTime < now && record.status === '待使用') {
            record.status = '已使用';
          }
          
          return record;
        });
        
        that.setData({
          bookingRecords: records
        });
        
        // 保存更新后的记录
        wx.setStorage({
          key: 'bookingRecords',
          data: records
        });
      },
      fail: function() {
        that.setData({
          bookingRecords: []
        });
      }
    });
  },

  // 取消预约
  cancelBooking: function(e) {
    const id = e.currentTarget.dataset.id;
    const that = this;
    
    wx.showModal({
      title: '取消预约',
      content: '确定要取消这个预约吗？',
      success: function(res) {
        if (res.confirm) {
          that.removeBookingRecord(id);
        }
      }
    });
  },

  // 移除预约记录
  removeBookingRecord: function(id) {
    wx.getStorage({
      key: 'bookingRecords',
      success: (res) => {
        const records = res.data.filter(record => record.id != id);
        wx.setStorage({
          key: 'bookingRecords',
          data: records
        });
        
        // 更新页面数据
        this.setData({
          bookingRecords: records
        });
        
        wx.showToast({
          title: '取消成功',
          icon: 'success'
        });
      }
    });
  },

  // 返回首页
  goToIndex: function() {
    wx.navigateBack();
  }
})